<template>
  <a-modal
    :visible="visible"
    :title="dialogTitle + originData?.name + ' 团队'"
    :unmount-on-close="true"
    :mask-closable="false"
    width="900px"
    @before-ok="handleBeforeOk"
    @cancel="handleCancel"
  >
    <a-form
      ref="teamRef"
      :model="formData"
      label-align="left"
      auto-label-width
      :disabled="handleType === 'view'"
      class="edit-form"
    >
      <a-row class="interval-row">
        <a-col :span="12">
          <a-form-item
            field="name"
            label="团队名称"
            label-col-flex="auto"
            validate-trigger="input"
            :rules="[
              {
                required: true,
                message: '团队名称必填',
              },
            ]"
          >
            <a-input v-model="formData.name" placeholder="请输入" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="userIds" label="团队成员" label-col-flex="auto">
            <user-selector
              v-model="formData.userIds"
              :project-id="formData.projectId"
              multiple
              @change="handleUsersChange"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item field="role" label="权限级别">
        <template #label>
          <img class="image" :src="infoImg" />
          <span class="title-text">权限级别</span>
        </template>
        <span>{{ getPermissionText(formData.role) }}</span>
        <permission-icon :active-count="formData.role" class="mini-icon" />
      </a-form-item>

      <a-table
        :loading="loading"
        :columns="(handleType === 'view' ? teamColumnsView  : teamColumnsEdit) as TableColumnData[]"
        :data="formData.teamUsers"
        :scroll="scrollConfig"
        :bordered="false"
        :pagination="false"
        class="people-table"
      >
        <template #index="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
        <template #role="{ record }">
          <template v-if="handleType === 'view'">
            {{ getPermissionText(record.role) }}
          </template>
          <template v-else>
            <a-select v-model="record.role" :options="options" />
          </template>
        </template>
        <template #operations="{ record }">
          <a-button
            type="text"
            size="small"
            status="danger"
            @click="handleDelete(record.id)"
            >删除</a-button
          >
        </template>
      </a-table>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
  import { computed, ref, watch } from 'vue';
  import useLoading from '@/hooks/loading';
  import { FormInstance } from '@arco-design/web-vue/es/form';
  import { Message } from '@arco-design/web-vue';
  import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
  import infoImg from '@/assets/images/project-setting/info-icon@2x.png';
  import UserSelector from '@/components/user-selector/index.vue';
  import PermissionIcon from './permission-icon.vue';
  import { TeamRecord, UserRecord, queryTeamDetail, updateTeam } from '../api';

  const props = defineProps({
    visible: {
      type: Boolean,
      default: false,
    },
    handleType: {
      type: String,
      default: 'view',
    },
    originData: {
      type: Object,
      require: true,
    },
  });
  const emit = defineEmits(['update:visible', 'refresh']);

  const { loading, setLoading } = useLoading(true);
  const teamRef = ref<FormInstance>();
  const dialogTitle = computed(() => {
    return props.handleType === 'view' ? '查看 ' : '编辑 ';
  });
  const formData = ref<TeamRecord>({ ...props.originData } as TeamRecord);

  // 通过人员列表，生成用户id字符串（用于传给选人组件）
  const getTeamUserIds = () => {
    return formData.value.teamUsers
      ?.map((user: UserRecord) => {
        return user.id;
      })
      .join(',');
  };

  // 查询团队数据
  const getTeamDetail = () => {
    setLoading(true);
    const params = {
      id: props.originData?.id,
    };
    queryTeamDetail(params)
      .then((res) => {
        formData.value = res.data || {};
        // 为选人组件赋初始值
        formData.value.userIds = getTeamUserIds();
      })
      .catch((err) => {
        // eslint-disable-next-line no-console
        console.log(err);
      })
      .finally(() => {
        setLoading(false);
      });
  };

  watch(
    () => props.originData,
    (n) => {
      formData.value = { ...n } as TeamRecord;
      getTeamDetail();
    }
  );

  // 监听选人组件变化，同步更新人员列表
  const handleUsersChange = (newUserAry: Array<UserRecord>) => {
    const newIds = newUserAry
      ?.map((user: UserRecord) => {
        return user.id;
      })
      .join(',');
    const oldIds = formData.value.teamUsers
      ?.map((user: UserRecord) => {
        return user.id;
      })
      .join(',');

    if (newIds !== oldIds) {
      const teamUserAry = newUserAry.map((newUser: UserRecord) => {
        const oldTeamUserObj = formData.value.teamUsers?.find(
          (oldUser: UserRecord) => {
            return oldUser.id === newUser.id;
          }
        );
        if (oldTeamUserObj) {
          return { ...oldTeamUserObj };
        }
        return {
          id: newUser.id,
          name: newUser.name,
          role: formData.value.role,
        };
      });

      formData.value.teamUsers = teamUserAry;
    }
  };

  const options = [
    {
      label: '查看',
      value: 1,
    },
    {
      label: '编辑',
      value: 2,
    },
    {
      label: '共享',
      value: 3,
    },
    {
      label: '管理',
      value: 4,
    },
  ];

  // 权限数值转文字
  const getPermissionText = (role: number) => {
    return options.filter((item) => item.value === role)[0]?.label;
  };

  // 人员列表
  const scrollConfig = {
    y: 234,
  };

  const teamColumnsView = [
    {
      title: '序号',
      dataIndex: 'index',
      slotName: 'index',
      align: 'center',
      width: 62,
    },
    {
      title: '名称',
      dataIndex: 'name',
      slotName: 'name',
    },
    {
      title: '权限级别',
      dataIndex: 'role',
      slotName: 'role',
      align: 'center',
      width: 160,
    },
  ];

  const teamColumnsEdit = [
    ...teamColumnsView,
    {
      title: '操作',
      dataIndex: '',
      slotName: 'operations',
      align: 'center',
      width: 90,
    },
  ];

  // 删除人员按钮点击事件
  const handleDelete = (id: string) => {
    // 删除列表人员
    formData.value.teamUsers = formData.value.teamUsers?.filter(
      (user: UserRecord) => {
        return user.id !== id;
      }
    );
    // 删除选人组件人员
    formData.value.userIds = getTeamUserIds();
  };

  // 调用接口修改团队信息
  const handleEdit = async () => {
    try {
      const params = {
        ...formData.value,
        count: formData.value.teamUsers?.length || 0,
      };
      delete params.userIds;

      const res = await updateTeam(params);
      return !!res.status;
    } catch (error) {
      return false;
    }
  };

  // 确定按钮点击事件
  const handleBeforeOk = async (done: any) => {
    if (props.handleType === 'view') {
      // 查看
      emit('update:visible', false);
    } else {
      // 编辑
      const res = await teamRef.value?.validate();
      if (!res) {
        const flg = await handleEdit();
        if (flg) {
          Message.success('编辑成功');
          emit('update:visible', false);
          emit('refresh');
        }
        done();
      }
    }
  };

  // 取消按钮点击事件
  const handleCancel = () => {
    emit('update:visible', false);
  };
</script>

<style lang="less" scoped>
  .edit-form {
    :deep(.arco-form-item) {
      margin-bottom: 16px;
    }
  }
  .image {
    margin-right: 8px;
    width: 18px;
    height: 18px;
    vertical-align: text-top;
  }

  .title-text {
    font-size: 16px;
    line-height: 16px;
  }

  :deep(.permission-item) {
    .arco-radio-label {
      display: flex;
    }
  }

  .interval-row .arco-col:last-child {
    padding-left: 29px;
  }

  .interval-row .arco-col:first-child {
    padding-right: 29px;
  }

  :deep(.mini-icon .icon) {
    width: 22px;
  }

  .people-table {
    min-height: 274px;
  }
</style>
